package com.gpframework.module.common.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.constant.BrandConstants;
import com.gpframework.common.constant.CacheConstants;
import com.gpframework.common.constant.Constants;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.brand.domain.BrandWxMenu;
import com.gpframework.module.brand.domain.req.BrandWxMenuAdd;
import com.gpframework.module.brand.service.IBrandWxMenuService;
import com.gpframework.module.common.domain.CommonWxMenu;
import com.gpframework.module.common.domain.req.CommonWxMenuReq;
import com.gpframework.module.common.domain.vo.CommonWxMenuVo;
import com.gpframework.module.common.mapper.CommonWxMenuMapper;
import com.gpframework.module.common.service.ICommonWxMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CommonWxMenu
 * @Author gpframework
 * @Date 2023-08-15
 * @Version 1.0.0
 * @Description 小程序权限Service业务层处理
 */
@Service
public class CommonWxMenuServiceImpl extends ServiceImpl<CommonWxMenuMapper, CommonWxMenu> implements ICommonWxMenuService {

    @Autowired
    private IBrandWxMenuService brandWxMenuService;

    @Autowired
    private RedisCache redisCache;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2023-08-15
     * @Param [lqw]
     * @Return List<CommonWxMenuVo>
     */
    @Override
    public List<CommonWxMenuVo> listVo(QueryWrapper<CommonWxMenu> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2023-08-15
     * @Param [id]
     * @Return CommonWxMenuVo
     */
    @Override
    public CommonWxMenuVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    /**
     * 获取门店小程序权限 pc（是否有开启授权都会显示所有权限列表且返回是否授权标识）
     *
     * @param commonWxMenuReq
     * @return
     */
    @Override
    public List<CommonWxMenuVo> findList(CommonWxMenuReq commonWxMenuReq) {
        //缓存key
        String key = CacheConstants.BRAND_WX_MENU_PC + commonWxMenuReq.getBrandId() + CacheConstants.PACKET_IDENTIFICATION + commonWxMenuReq.getStoreId();
        //获取缓存
        String wxMenuVoListJson = redisCache.getCacheObject(key);
        //返回的数据
        List<CommonWxMenuVo> wxMenuVoList;
        if (StringUtils.isEmpty(wxMenuVoListJson)) {
            //数据库获取权限
            wxMenuVoList = this.baseMapper.findList(commonWxMenuReq);
            //保存缓存
            redisCache.setCacheObject(key, JSONObject.toJSONString(wxMenuVoList));
            //设置缓存时间(一天)
            redisCache.expire(key, CacheConstants.CACHE_OVERDUE_ONE_DAY, TimeUnit.HOURS);
            return wxMenuVoList;
        }
        //解析json数据
        wxMenuVoList = JSONObject.parseArray(wxMenuVoListJson, CommonWxMenuVo.class);
        return wxMenuVoList;
    }

    /**
     * 获取门店小程序权限 微信 （只返回门店的授权列表）
     *
     * @param commonWxMenuReq
     * @return
     */
    @Override
    public List<String> getStoreComponentList(CommonWxMenuReq commonWxMenuReq) {
        //缓存key
        String key = CacheConstants.BRAND_WX_MENU_WX + commonWxMenuReq.getBrandId() + CacheConstants.PACKET_IDENTIFICATION + commonWxMenuReq.getStoreId();
        //获取缓存
        String wxMenuVoListJson = redisCache.getCacheObject(key);
        //返回的数据
        List<String> componentList;
        if (StringUtils.isEmpty(wxMenuVoListJson)) {
            //数据库获取权限
            componentList = this.baseMapper.getStoreComponentList(commonWxMenuReq);
            if (StringUtils.isNotEmpty(componentList) && componentList.size() > 0) {
                //保存缓存
                redisCache.setCacheObject(key, JSONObject.toJSONString(componentList));
                //设置缓存时间(一天)
                redisCache.expire(key, CacheConstants.CACHE_OVERDUE_ONE_DAY, TimeUnit.HOURS);
            }
            return componentList;
        }
        //解析json数据
        componentList = JSONObject.parseArray(wxMenuVoListJson, String.class);
        return componentList;
    }

    /**
     * 添加门店菜单权限
     *
     * @param brandWxMenuAdd
     * @return
     */
    @Override
    public boolean saveStoreWxMenu(BrandWxMenuAdd brandWxMenuAdd) {
        //缓存key
        String brandKey = CacheConstants.CACHE_BRAND_STORE_LIST + brandWxMenuAdd.getBrandId();
        String keyPc = CacheConstants.BRAND_WX_MENU_PC + brandWxMenuAdd.getBrandId() + CacheConstants.PACKET_IDENTIFICATION + brandWxMenuAdd.getStoreId();
        String keyWx = CacheConstants.BRAND_WX_MENU_WX + brandWxMenuAdd.getBrandId() + CacheConstants.PACKET_IDENTIFICATION + brandWxMenuAdd.getStoreId();
        //删除缓存
        redisCache.deleteObject(brandKey);
        redisCache.deleteObject(keyPc);
        redisCache.deleteObject(keyWx);
        BrandWxMenu brandWxMenu = new BrandWxMenu();
        brandWxMenu.setBrandId(brandWxMenuAdd.getBrandId());
        brandWxMenu.setStoreId(brandWxMenuAdd.getStoreId());
        //删除原权限标识记录
        brandWxMenuService.delByBrandIdAndStoreId(brandWxMenu);
        //添加门店权限标识
        List<Long> wxMenuIdList = brandWxMenuAdd.getWxMenuIdList();
        if (StringUtils.isNotEmpty(wxMenuIdList) && wxMenuIdList.size() > 0) {
            List<BrandWxMenu> brandWxMenuList = new ArrayList<>();
            for (Long menuId : wxMenuIdList) {
                if (StringUtils.isNull(menuId)) {
                    continue;
                }
                brandWxMenu = Convert.convert(new TypeReference<BrandWxMenu>() {
                }, brandWxMenuAdd);
                brandWxMenu.setWxMenuId(menuId);
                brandWxMenuList.add(brandWxMenu);
            }
            brandWxMenuService.saveBatch(brandWxMenuList, 500);
        }
        //删除缓存
        redisCache.deleteObject(brandKey);
        redisCache.deleteObject(keyPc);
        redisCache.deleteObject(keyWx);
        return true;
    }

    /**
     * 小程序模块显示默认参数
     *
     * @param wxMenuReq
     */
    @Override
    public boolean initializeWxMenu(CommonWxMenuReq wxMenuReq) {
        QueryWrapper<BrandWxMenu> lqw = new QueryWrapper<>();
        lqw.eq("gp.del_status", Constants.DEL_STATUS_FALSE);
        lqw.eq("gp.brand_id", BrandConstants.DEFAULT_BRAND_ID);
        lqw.eq("gp.store_id", BrandConstants.DEFAULT_BRAND_ID);
        //获取默认菜单
        List<BrandWxMenu> wxMenuVoList = brandWxMenuService.listVo(lqw);
        List<Long> wxMenuIdList = new ArrayList<>();
        if (StringUtils.isNotEmpty(wxMenuVoList) && wxMenuVoList.size() > 0) {
            for (BrandWxMenu wxMenu : wxMenuVoList) {
                wxMenuIdList.add(wxMenu.getWxMenuId());
            }
        }
        BrandWxMenuAdd brandWxMenuAdd = new BrandWxMenuAdd();
        brandWxMenuAdd.setBrandId(wxMenuReq.getBrandId());
        brandWxMenuAdd.setStoreId(wxMenuReq.getStoreId());
        brandWxMenuAdd.setWxMenuIdList(wxMenuIdList);
        //添加门店菜单权限
        this.saveStoreWxMenu(brandWxMenuAdd);
        return true;
    }
}
